package inits

import (
	"api-getaway/basic/config"
	"api-getaway/basic/global"
	__ "api-getaway/proto"
	"encoding/json"
	"github.com/nacos-group/nacos-sdk-go/v2/clients"
	"github.com/nacos-group/nacos-sdk-go/v2/common/constant"
	"github.com/nacos-group/nacos-sdk-go/v2/vo"
	"google.golang.org/grpc"
	"google.golang.org/grpc/credentials/insecure"
	"log"
)

func init() {
	config.Init()
	InitNacos()
	InitGrpc()
}

func InitNacos() {

	appends := config.AppConfig
	clientConfig := constant.ClientConfig{
		NamespaceId:         appends.NamespaceId, //we can create multiple clients with different namespaceId to support multiple namespace.When namespace is public, fill in the blank string here.
		TimeoutMs:           5000,
		NotLoadCacheAtStart: true,
		LogDir:              "/tmp/nacos/log",
		CacheDir:            "/tmp/nacos/cache",
		LogLevel:            "debug",
	}

	serverConfigs := []constant.ServerConfig{
		{
			IpAddr:      appends.IpAddr,
			ContextPath: "/nacos",
			Port:        uint64(appends.Port),
			Scheme:      "http",
		},
	}

	configClient, _ := clients.CreateConfigClient(map[string]interface{}{
		"serverConfigs": serverConfigs,
		"clientConfig":  clientConfig,
	})

	content, _ := configClient.GetConfig(vo.ConfigParam{
		DataId: appends.DataId,
		Group:  appends.Group,
	})

	var good config.Config
	json.Unmarshal([]byte(content), &good)

	global.GoodNacos = good
}

func InitGrpc() {
	conn, err := grpc.NewClient("localhost:10002", grpc.WithTransportCredentials(insecure.NewCredentials()))
	if err != nil {
		log.Fatalf("did not connect: %v", err)
	}
	client := __.NewGoodServerClient(conn)

	global.GoodClient = client
}
